package controller

import (
	"hello/service"
	"hello/util"
	"log"
	"net/http"
	"strconv"
)

func init()  {
	//把它放到这里的原因是，service的node文件被引用了两次，如果直接放到node文件里，会被初始化两次
	go service.UpdReceive()
	go service.UpdSend()
}

//ws://127.0.0.1/chat?id=1&token=xxx

func Chart(write http.ResponseWriter, request *http.Request)  {
	//检验token是否合法
	query := request.URL.Query()
	id := query.Get("id")
	token := query.Get("token")
	userId, _ := strconv.ParseInt(id, 10, 64)
	validate := userService.CheckToken(userId, token)
	if !validate {
		log.Println("ID: " + id + "; TOKEN:" + token + "； 不对应")
		return
	}
	//获取连接
	conn, err := util.NewWebsocketConn(validate, write, request)
	if err != nil {
		log.Println(err)
		return
	}
	node := service.NewNode(conn)

	//节点绑定到用户
	node.BindUser(userId)

	//协程绑定发送和接受数据
	//go node.Send()

	go node.Receive()

	//测试
	//testSendMsg(node)

}

func testSendMsg(node service.NodeService)  {
	data := []byte("hello world")
	node.DataQueue <- data
}